package my.dao;

import my.dao.impl.DaoConfig;
import my.dao.impl.NoTransactionDaoImpl;
import my.dao.impl.TransactionDaoImpl;

/**
 * @version 3.0 
 * @author 夏冬琦
 *
 */
public class DaoCreater {
	
	
	
	/**
	 * 依据事务配置创建Dao对象
	 * @return 返回Dao对象
	 */
	public static Dao createDao()throws DaoException{
		return DaoConfig.getInstance().useTransaction()?createDao(Dao.TX_USE_YES):createDao(Dao.TX_USE_NO);
	}
	
	public static Dao createDao(int tx_use) throws DaoException{
		switch(tx_use){
			case Dao.TX_USE_YES:return new TransactionDaoImpl();
			case Dao.TX_USE_NO:return new NoTransactionDaoImpl();
			default:throw new DaoException("不支持的方法参数！");
		}
	}
	
	private static final ThreadLocal<Dao> threadLocal=new ThreadLocal<Dao>();	
	
	public static Dao currentDao() throws DaoException{
		Dao dao=threadLocal.get();
		if(dao==null){
			try {
				dao=DaoCreater.createDao();
				System.out.println("当前Dao创建成功。");
				if(dao instanceof TransactionDaoImpl){
					dao.beginTransaction();
					System.out.println("当前Dao开启事务成功。");
				}
			} catch (DaoException e) {
				throw new CurrentDaoInitialException(e);
			}
			threadLocal.set(dao);
		}
		return dao;
	}
	
	private static void closeCurrentDao()throws DaoException{
		currentDao().close();
		threadLocal.remove();
		System.out.println("当前Dao关闭。");
	}
	
	public static void commitCurrentTx()throws DaoException{
		if(currentDao() instanceof TransactionDaoImpl){
			currentDao().commitTransaction();
			System.out.println("当前Dao提交事务成功。");
		}
		closeCurrentDao();
	}
	
	public static void rollbackCurrentTx(){
		try {
			if(currentDao() instanceof TransactionDaoImpl){
				currentDao().rollbackTransaction();
				System.out.println("当前Dao回滚事务。");
			}			
		}catch(DaoException e){
			e.printStackTrace();
			throw e;
		}finally{
			closeCurrentDao();
		}
	}
	
	
	
	
	
	private DaoCreater(){}
	
	public static void main(String[] args) {
		
		Dao dao=DaoCreater.createDao();
		dao.beginTransaction();
		
		dao.update("delete from student ");
		PreSQL presql=dao.preSQL("insert into student values(?,?,?)");
		for(int i=200;i<300;i++){
			presql.update(i,"姓名"+i,i);
		}
		
		System.out.println(dao.queryMapList("select * from student").toString());
		
		dao.commitTransaction();
		
		dao.close();
		/*
		presql=dao.preSQL("insert into student values(?,?,?)");
		for(int i=500;i<600;i++){
			presql.update(i,"姓名"+i,i);
		}
		*/
	}


}
